import { Component, Vue } from "vue-property-decorator";
import { Pagination } from "@/models/pagination";
import { Constant } from "@/constant";
import { ColumnSort } from "@/models/column-sort";

@Component
export class PaginationMixin extends Vue {
  DEFAULT_SORT: string = "lastModifiedDate," + Constant.DESC;
  pagination = new Pagination().toJson();

  created() {
    this.pagination.sort = this.DEFAULT_SORT;
    this.pagination.onChange = (pageNumber: number) => {
      this.pagination.current = pageNumber;
      this.$store.commit("SET_PAGE", pageNumber);
      this.pagination.getRecords();
    };
    this.pagination.onShowSizeChange = (pageNumber: number, pageSize: number) => {
      this.pagination.current = 1;
      this.pagination.pageSize = pageSize;
      this.$store.commit("SET_PAGE", 1);
      this.$store.commit("SET_PAGE_SIZE", pageSize);
      this.pagination.getRecords();
    };
    this.pagination.showTotal = () => {
      return `${this.$t("totalItems", { items: this.pagination.total })}`;
    };
  }

  onSortChange(page: Pagination, filters: object, sorter: ColumnSort) {
    if (sorter.order) {
      this.pagination.sort = sorter.columnKey + "," + (Constant.ASCEND === sorter.order ? Constant.ASC : Constant.DESC);
    } else {
      this.pagination.sort = this.DEFAULT_SORT;
    }
    this.pagination.getRecords();
  }

  resetPageNumber() {
    this.pagination.current = 1;
    this.pagination.sort = this.DEFAULT_SORT;
    this.$store.commit("SET_PAGE", 1);
    this.pagination.getRecords();
  }
}

export default PaginationMixin;
